package db;

import com.google.gson.Gson;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class Db extends HttpServlet {
    private StudentDao studentDao = new StudentDao();

    public static void main(String[] args) {
        Db db = new Db();
        for (int i = 1; i < 100; i++) {
            Student student = new Student();
            student.name = "测试姓名" + i;
            student.major = "专业" + i;
            student.clasz = "班级" + i;
            student.studentId = 128748+i+"";
            db.studentDao.addStudent(student);
        }

    }
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String option = req.getParameter("option");
        if (option == null)
            return;
        switch (option) {
            case "query":
                doQuery(req, resp);
                break;
            case "add":
                doAdd(req, resp);
                break;
            case "remove":
                doRemove(req, resp);
                break;
        }


    }

    private void doQuery(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException  {
        PrintWriter writer = response.getWriter();
        Gson gson = new Gson();
        String json = gson.toJson(studentDao.getStudents());
        writer.write(json);
    }
    private void doAdd(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException  {
        Student student = new Student();
        student.name = request.getParameter("name");
        student.studentId = request.getParameter("studentId");
        student.major = request.getParameter("major");
        student.clasz = request.getParameter("clasz");
        int id = studentDao.addStudent(student);
        PrintWriter writer = response.getWriter();
        writer.write(id + "");
    }
    private void doRemove(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String id = request.getParameter("id");
        studentDao.removeStudentById(id);
    }

}
